﻿using HuaHan.WorkTicket.Infrastructure.ExceptionHandler;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace WorkTicket.Website.Common
{
    public class CustomHandleErrorAttribute : FilterAttribute,IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            //Don't bother if custom errors are turned off or if the exception is already handled
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
                return;

            ILog log = LogManager.GetLogger("MyLogger");
            //Get currently logged in user (null if anonymous)
            

            //Log the exception and get a correlation id
            //Guid? correlationId = Logger.LogException(…)
            Guid? correlationId = Guid.NewGuid();
            var httpException = filterContext.Exception as HttpException;

            ExceptionMessage exceptionMessage = new ExceptionMessage(filterContext.Exception, correlationId.Value);
            log.Error(exceptionMessage.ErrorDetails);

            //Set the view correctly depending if it's an AJAX request or not
            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        error = true,
                        correlationId = correlationId
                    }
                };
            }
            else
            {
                string view = "~/Views/Error/Index.cshtml";
                if (httpException != null)
                {
                    if (httpException.GetHttpCode() == 404)
                    {
                        view = "~/Views/Error/NotFound.cshtml";
                    }
                }

                filterContext.Result = new ViewResult
                {
                    ViewName = view,
                    ViewData = new ViewDataDictionary<Guid?>(correlationId)
                };
            }

            //If it's not a httpException, just set the status code as 500
            if (httpException != null)
            {
                filterContext.HttpContext.Response.StatusCode = httpException.GetHttpCode();
            }
            else
            {
                filterContext.HttpContext.Response.StatusCode = 500;
            }

            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}